package com.imooc.web.async;

import java.util.concurrent.Callable;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

/**
 * @ClassName AsyncController.java
 * @Description 多线程测试类
 * @author Jon
 * @date 2018年5月30日 下午3:59:52
 */
@RestController
public class AsyncController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private MockQueue mockQueue;
	
	@Autowired
	private DeferredResultHolder deferredResultHolder;
	
	/**   
	 * Description  		跨服务异步操作
	 * @return
	 * @throws Exception  
	 */ 
	@RequestMapping("/order/deferredresult")
	public DeferredResult<String> deferredresultOrder() throws Exception {
		logger.info("主线程开始");
		
		String orderNumber = RandomStringUtils.randomNumeric(8);//随机生成八位订单号
		mockQueue.setPlaceOrder(orderNumber);
		
		DeferredResult<String> result = new DeferredResult<>();
		deferredResultHolder.getMap().put(orderNumber, result);
		
		logger.info("主线程结束");
		return result;
	}
	 
	/**   
	 * Description  		普通异步操作
	 * @return
	 * @throws Exception  
	 */ 
	@RequestMapping("/order/runnable")
	public Callable<String> runnableOrder() throws Exception {
		logger.info("主线程开始");
		//主线程创建父线程
		Callable<String> result = new Callable<String>() {
			@Override
			public String call() throws Exception {
				logger.info("副线程开始");
				Thread.sleep(1000);
				logger.info("副线程结束");
				return "success";
			}
		};
		logger.info("主线程结束");
		return result;
	}
}
